package dice.sinanya.db.diceLog;

import com.forte.qqrobot.log.LogLevel;
import dice.sinanya.db.tools.SqliteUtil;
import dice.sinanya.entity.EntityLogList;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class SelectDiceLog {
    private static final Logger logger = LogManager.getLogger(SelectDiceLog.class.getName());
    SqliteUtil sqliteUtil;
    Connection connection;
    int len=80;

    public SelectDiceLog() {
        sqliteUtil = new SqliteUtil();
        initCon();
        initDb();
    }

    private void initCon() {
        do {
            connection = sqliteUtil.getDiceLogConnection();
        } while (connection == null);
    }

    private void initDb() {
        try (Statement statement = connection.createStatement()) {
            statement.executeUpdate("create table if not exists diceLog(time datetime,level varchar(200),info longtext,PRIMARY KEY (time));");
        } catch (SQLException sqlException) {
            logger.error(sqlException.getMessage(), sqlException);
        }
    }

    public ArrayList<EntityLogList> selectDiceLogList() {
        ArrayList<EntityLogList> logLists = new ArrayList<>();
        try {
            if (connection == null || connection.isClosed()) {
                initCon();
            }
        } catch (SQLException sqlException) {
            sqlException.printStackTrace();
        }
        //language=SQLite
        String sql = "select time,level,info from diceLog order by time desc limit 3000;";
        try (Statement statement = connection.createStatement()) {
            try (ResultSet resultSet = statement.executeQuery(sql)) {
                while (resultSet.next()) {
                    EntityLogList logList = new EntityLogList();
                    logList.setTimestamp(resultSet.getTimestamp("time"));
                    logList.setLevel(resultSet.getString("level"));
                    logList.setInfo(resultSet.getString("info"));
                    logLists.add(logList);
                }
            }
        } catch (SQLException sqlException) {
            logger.error(sqlException.getMessage(), sqlException);
        }
        Collections.reverse(logLists);
        return logLists;
    }



}
